<template>
	<el-upload 
		multiple 
		:drag="drag"
		:limit="limit"
		:headers="headers"
		:action="$util.baseUrl + uploadUrl" 
		:show-file-list="false" 
		:accept="formats.map(e => '.' + e).join(',')"  
		:before-upload="beforeUpload"
		:on-success="onUploaded"
		:class="{'btn-upload': !drag}"
		:style="{width: width, height: height, lineHeight: height}">

		<template v-if="drag">
			<i class="el-icon-upload"></i>
			<div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
			<div class="el-upload__tip" slot="tip">请选择{{formats.join('/')}}文件，大小不超过2mb</div>
		</template>
		<i v-else class="el-icon-plus"></i>

	</el-upload>
</template>

<script>
	export default {
		props: {
			drag: {
				type: Boolean,
				default: false
			},
			limit: Number,
			uploadUrl: String,
			type: String,
			width: {
				type: String,
				default: 'auto'
			},
			height: {
				type: String,
				default: 'auto'
			}
		},
		data() {
			return {
				formats: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'jfif']
			}
		},
		computed: {
			headers() {
				return {
					token: this.$store.getters.token,
					type: this.type
				}
			}
		},
		methods: {
			beforeUpload(file) {
				const format = file.type.split('/')[1];
				if (!this.formats.includes(format)) return this.$util.msg(`图片仅支持${this.formats.join('/')}格式`);
				if (file.size / 1024 / 1024 > 2) return this.$util.msg('图片大小不能超过2MB');
			
				this.uploading = this.$loading({
					text: '上传中...',
					body: true
				});
				return true;
			},
			onUploaded(res) {
				this.uploading.close();
			
				if (res.state == 'ok') {
					this.$emit('change', res.url);
				} else {
					this.$util.msg(res.msg);
				}
			}
		}
	}
</script>

<style lang="scss">
	.btn-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		display: flex;
		margin-bottom: 15px;
		
		&:hover {
			border-color: $color-primary;
		}
		
		.el-upload {
			flex: 1;
			
			.el-icon-plus {
				font-size: 28px;
				color: #8c939d;
				text-align: center;
				line-height: 2;
			}
		}
	}
</style>
